<?php


namespace app\API\controller;

use think\Cache;
use think\Controller;
use think\Image;
use think\Log;
use think\Request;
use think\Session;

/**
 * 控制器基类
 * Class Base
 * @package app\API\controller
 */
class Base extends Controller
{
    //定义公用参数
    protected $validater; //用来验证参数
    protected $params; //过滤后符合要求的参数

    public function __construct()
    {
        // 指定允许其他域名访问
        header('Access-Control-Allow-Origin:*');  //支持全域名访问
        $allow_origin = [
            'http://localhost:8080',
        ];
        $origin       = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';  //跨域访问的时候才会存在此字段
//        header('Access-Control-Allow-Origin:http://www.whatgoingon.cn');//表示接受http://localhost:8080的请求
        if (in_array($origin, $allow_origin)) {
            header('Access-Control-Allow-Origin:' . $origin);
        }
//       else {
//            return;
//        }
        header('Access-Control-Allow-Methods:POST,GET'); //支持的http动作
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 1000');
        header('Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept, Authorization, token, App-Id');  //响应头 请按照自己需求添加。
        if (strtolower($_SERVER['REQUEST_METHOD']) == 'options') {
            exit;
        }
        // 请求方式检测
//        var_dump(Request::instance());
//        die();
        $request = Request::instance();
//        $this->method  = strtolower($request->method());
        $this->params = json_decode($request->getInput(), true); //接收的参数

    }

    /***
     *返回信息
     * @param $code 状态码
     * @param string $msg 提示语
     * @param array $data 返回数据
     */
    public function return_msg($code, $msg = '', $data = [])
    {
        //组合数据
        $result['code'] = $code;
        $result['msg']  = $msg;
        $result['data'] = $data;
        //返回数据,并终止脚本
        echo json_encode($result, JSON_UNESCAPED_UNICODE);
        die;
    }


    /***
     * Desc :通用获取缓存数据
     * User : HAIYUN
     * Date : 2022-01-04 16:30
     * @param $key 缓存字段名
     * @return mixed
     */
    public function getCurrentTokenVar($key)
    {
        $token = Request::instance()->header('token');
        $vars  = Cache::get($token);
        if (!$vars) {
            $this->return_msg('40001', "Token过期或无效", []);
        } else {
            if(!is_array($vars)){
                //变成数组处理
                $vars = json_decode($vars,true);
            }
            if(array_key_exists($key,$vars)){
                return $vars[$key];
            }else{
                $this->return_msg('40002',"尝试获取的Token不存在",[]);
            }
        }
    }

    /***
     * 生成36位uuid
     * @return string 36位uuid
     */
    public function get_uuid()
    {
        if (function_exists('com_create_guid')) {
            return com_create_guid();
        }
        mt_srand((double)microtime() * 10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid   = substr($charid, 0, 8) . $hyphen
            . substr($charid, 8, 4) . $hyphen
            . substr($charid, 12, 4) . $hyphen
            . substr($charid, 16, 4) . $hyphen
            . substr($charid, 20, 12);
        return $uuid;
    }

    /***
     * Desc :生产随机字符串
     * User : HAIYUN
     * Date : 2022-01-04 14:38
     * @param $length
     * @return string
     */
    public function getRandStr($length)
    {
        //字符组合
        $str     = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len     = strlen($str) - 1;
        $randstr = '';
        for ($i = 0; $i < $length; $i++) {
            $num     = mt_rand(0, $len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

    /**
     * 发送HTTP请求方法
     * @param string $url 请求URL
     * @param array $params 请求参数
     * @param string $method 请求方法GET/POST
     * @return array  $data   响应数据
     */
    public function curl_request($url, $params, $method = 'GET', $header = array(), $multi = false)
    {
        $opts = array(
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER     => $header
        );
        /* 根据请求类型设置特定参数 */
        switch (strtoupper($method)) {
            case 'GET':
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                break;
            case 'POST':
                //判断是否传输文件
                $params                   = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL]        = $url;
                $opts[CURLOPT_POST]       = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                throw new Exception('不支持的请求方式！');
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data  = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if ($error) throw new Exception('请求发生错误：' . $error);
        return $data;
    }

    /***
     * Desc :参数过滤，过滤掉不需要的信息
     * User : HAIYUN
     * Date : 2022-01-04 17:20
     * @return mixed
     */
    public function getDataByRule($arrays,$rules)
    {
        if(array_key_exists('user_id',$arrays) || array_key_exists('uid',$arrays)){
            $this->return_msg("10002","包含恶意参数uid或user_id");
        }
        $new_array = [];
//        $this->return_msg("123123","ces1",$rules);
        foreach ($rules as $key => $value){
            $new_array[$value[0]] = $arrays[$value[0]];
        }
        return $new_array;
    }

    /***
     * 图片上传
     */
    public function img_upload($path,$type)
    {
        //获取上传图片并保存到对应目录
        $file = request()->file('image');
        $arr  = [
            'code' => "00000",
            'msg'  => '上传图片成功',
            'data' => [],
        ];
        $info = $file->move($path);
        if ($info) {
//            $save_path = DS . 'image' . DS . $type . DS . $info->getSaveName();
//            \image\avater\20220111\4f476ad9c47edeb159f8c24958b71058.png
            $save_path = '/' . 'image' . '/' . $type . '/' . $info->getSaveName();
            $save_path = str_replace('\\','/',$save_path); //替换斜杠
//            echo $save_path;
//            die();
            $this->img_edit($save_path,$type);
            $arr['data'] = $save_path;
        } else {
            $arr['code'] = "10004";
            $arr['msg']  =  $file->getError();
        }
        echo json_encode($arr);

    }

    /***
     * Desc :裁剪图片
     * User : HAIYUN
     * Date : 2022-01-05 20:31
     * @param $path
     * @param $type
     */
    public function img_edit($path, $type)
    {
        $edit_url = ROOT_PATH . 'public' . $path;
//        var_dump($edit_url);
//        die();
        $image = Image::open($edit_url);
        switch ($type){
            case "avater" :
                $image->thumb(132,132,Image::THUMB_CENTER)->save($edit_url);
                break;
        }
    }

    /***
     * Desc:生成订单号
     * User: HAIYUN
     * Date: 2022/2/25 14:50
     */
    public function get_order_uuid() {
       $code =  date('Ymd').substr(implode(NULL,array_map('ord',str_split( substr(uniqid(), 7, 13) , 1))), 0, 8);
       return $code;
    }

    /***
     * Desc:计算两个日期的差
     * User: HAIYUN
     * Date: 2022/3/2 11:51
     */
    public function diffBetweenTwoDays ($start,$end) {
        $second1 = strtotime($start);
        $second2 = strtotime($end);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ceil(($second1 - $second2) / 3600)  * config('setting.unit_price');
    }
}